import React, { useState } from 'react';
import './AppPage.css';

interface AppData {
  id: number;
  name: string;
  category: string;
  status: string;
  createdAt: string;
}

interface VideoData {
  id: number;
  title: string;
  duration: string;
  views: string;
  thumbnail: string;
}

const AppsPage: React.FC = () => {
  // 模拟数据
  const initialAppData: AppData[] = [
    { id: 1, name: '数据分析应用', category: '工具类', status: '运行中', createdAt: '2023-05-15' },
    { id: 2, name: '内容管理系统', category: '管理系统', status: '已停止', createdAt: '2023-06-20' },
    { id: 3, name: '用户画像平台', category: '分析类', status: '运行中', createdAt: '2023-07-10' },
    { id: 4, name: '推荐引擎', category: 'AI类', status: '维护中', createdAt: '2023-08-05' },
  ];

  const initialVideoData: VideoData[] = [
    { id: 1, title: '系统介绍视频', duration: '5:30', views: '1.2K', thumbnail: '' },
    { id: 2, title: '操作演示教程', duration: '8:45', views: '2.5K', thumbnail: '' },
    { id: 3, title: '新功能展示', duration: '6:15', views: '800', thumbnail: '' },
    { id: 4, title: '故障排查指南', duration: '12:20', views: '3.1K', thumbnail: '' },
  ];

  const [appData, setAppData] = useState<AppData[]>(initialAppData);
  const [videoData] = useState<VideoData[]>(initialVideoData);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentApp, setCurrentApp] = useState<AppData | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    category: '',
    status: '运行中',
  });
  // 添加确认删除对话框状态
  const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
  const [appToDelete, setAppToDelete] = useState<AppData | null>(null);
  // 添加视频播放模态框状态
  const [isVideoModalOpen, setIsVideoModalOpen] = useState(false);
  const [currentVideo, setCurrentVideo] = useState<VideoData | null>(null);

  // 打开添加模态框
  const handleAddClick = () => {
    setCurrentApp(null);
    setFormData({ name: '', category: '', status: '运行中' });
    setIsModalOpen(true);
  };

  // 打开编辑模态框
  const handleEditClick = (app: AppData) => {
    setCurrentApp(app);
    setFormData({
      name: app.name,
      category: app.category,
      status: app.status,
    });
    setIsModalOpen(true);
  };

  // 打开删除确认对话框
  const handleDeleteClick = (app: AppData) => {
    setAppToDelete(app);
    setIsDeleteConfirmOpen(true);
  };

  // 确认删除
  const confirmDelete = () => {
    if (appToDelete) {
      setAppData(appData.filter(app => app.id !== appToDelete.id));
      setIsDeleteConfirmOpen(false);
      setAppToDelete(null);
    }
  };

  // 取消删除
  const cancelDelete = () => {
    setIsDeleteConfirmOpen(false);
    setAppToDelete(null);
  };

  // 打开视频播放模态框
  const handleVideoClick = (video: VideoData) => {
    setCurrentVideo(video);
    setIsVideoModalOpen(true);
  };

  // 关闭视频播放模态框
  const closeVideoModal = () => {
    setIsVideoModalOpen(false);
    setCurrentVideo(null);
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  // 提交表单
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (currentApp) {
      // 编辑应用
      setAppData(appData.map(app => 
        app.id === currentApp.id 
          ? { ...app, ...formData } 
          : app
      ));
    } else {
      // 添加新应用
      const newApp: AppData = {
        id: Math.max(0, ...appData.map(a => a.id)) + 1,
        name: formData.name,
        category: formData.category,
        status: formData.status,
        createdAt: new Date().toISOString().split('T')[0],
      };
      setAppData([...appData, newApp]);
    }
    
    setIsModalOpen(false);
  };

  // 关闭模态框
  const closeModal = () => {
    setIsModalOpen(false);
  };

  return (
    <div className="apps-page">
      <div className="apps-header">
        <h1 className="apps-title">应用管理</h1>
        <div className="apps-actions">
          <button className="btn btn-primary" onClick={handleAddClick}>
            + 添加应用
          </button>
        </div>
      </div>

      {/* 数据表格 */}
      <div className="data-table-container">
        <div className="table-header">
          <h2 className="table-title">应用列表</h2>
        </div>
        <div className="table-wrapper">
          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>应用名称</th>
                <th>分类</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {appData.map(app => (
                <tr key={app.id}>
                  <td>{app.id}</td>
                  <td>{app.name}</td>
                  <td>{app.category}</td>
                  <td>
                    <span className={`status ${app.status}`}>
                      {app.status}
                    </span>
                  </td>
                  <td>{app.createdAt}</td>
                  <td className="actions-cell">
                    <button 
                      className="action-btn edit-btn" 
                      onClick={() => handleEditClick(app)}
                    >
                      编辑
                    </button>
                    <button 
                      className="action-btn delete-btn" 
                      onClick={() => handleDeleteClick(app)}
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 视频播放列表 */}
      <div className="video-section">
        <div className="video-header">
          <h2 className="video-title">教学视频</h2>
        </div>
        <div className="video-grid">
          {videoData.map(video => (
            <div className="video-card" key={video.id} onClick={() => handleVideoClick(video)}>
              <div className="video-thumbnail">
                <div className="play-icon">▶</div>
              </div>
              <div className="video-info">
                <h3 className="video-name">{video.title}</h3>
                <div className="video-meta">
                  <span>{video.duration}</span>
                  <span>{video.views} 次观看</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 添加/编辑模态框 */}
      {isModalOpen && (
        <div className="modal" onClick={closeModal}>
          <div className="modal-content" onClick={e => e.stopPropagation()}>
            <div className="modal-header">
              <h3 className="modal-title">{currentApp ? '编辑应用' : '添加应用'}</h3>
              <button className="close-btn" onClick={closeModal}>×</button>
            </div>
            <form onSubmit={handleSubmit}>
              <div className="modal-body">
                <div className="form-group">
                  <label className="form-label">应用名称</label>
                  <input
                    type="text"
                    name="name"
                    className="form-input"
                    value={formData.name}
                    onChange={handleInputChange}
                    required
                  />
                </div>
                <div className="form-group">
                  <label className="form-label">分类</label>
                  <input
                    type="text"
                    name="category"
                    className="form-input"
                    value={formData.category}
                    onChange={handleInputChange}
                    required
                  />
                </div>
                <div className="form-group">
                  <label className="form-label">状态</label>
                  <select
                    name="status"
                    className="form-input"
                    value={formData.status}
                    onChange={handleInputChange}
                  >
                    <option value="运行中">运行中</option>
                    <option value="已停止">已停止</option>
                    <option value="维护中">维护中</option>
                  </select>
                </div>
              </div>
              <div className="modal-footer">
                <button type="button" className="btn btn-secondary" onClick={closeModal}>
                  取消
                </button>
                <button type="submit" className="btn btn-primary">
                  {currentApp ? '更新' : '添加'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* 删除确认对话框 */}
      {isDeleteConfirmOpen && (
        <div className="modal" onClick={cancelDelete}>
          <div className="modal-content" onClick={e => e.stopPropagation()}>
            <div className="modal-header">
              <h3 className="modal-title">确认删除</h3>
              <button className="close-btn" onClick={cancelDelete}>×</button>
            </div>
            <div className="modal-body">
              <p>确定要删除应用 "{appToDelete?.name}" 吗？此操作不可撤销。</p>
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-secondary" onClick={cancelDelete}>
                取消
              </button>
              <button type="button" className="btn btn-primary delete-btn" onClick={confirmDelete}>
                确认删除
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 视频播放模态框 */}
      {isVideoModalOpen && currentVideo && (
        <div className="modal video-modal" onClick={closeVideoModal}>
          <div className="modal-content video-modal-content" onClick={e => e.stopPropagation()}>
            <div className="modal-header">
              <h3 className="modal-title">{currentVideo.title}</h3>
              <button className="close-btn" onClick={closeVideoModal}>×</button>
            </div>
            <div className="modal-body video-modal-body">
              <div className="video-player">
                <div className="video-placeholder">
                  视频播放区域 - {currentVideo.title}
                  <div className="play-icon-large">▶</div>
                </div>
              </div>
              <div className="video-details">
                <p>时长: {currentVideo.duration}</p>
                <p>观看次数: {currentVideo.views}</p>
              </div>
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-secondary" onClick={closeVideoModal}>
                关闭
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default AppsPage;